<?php

namespace Api\Controller;

use Common\Controller\AppframeController;

header('Content-Type: text/plain; charset=utf-8');
class ZhifuController extends AppframeController{


        //支付

    function zhifu(){
        $from = I("from");//来自谁的支付
//        $from = 1;
        $uid = I("uid");      //用户id
//        $uid = 1;
        $order_num = 'ZHP'.time().$uid;     //订单编号

        $pay = I("type");
//        $pay = 1;
        if($pay ==1){
            $pay_money = '0.01';
        }elseif($pay==2){
            $pay_money = '0.02';
        }elseif($pay==3){
            $pay_money = '0.03';
        }elseif($pay==4){
            $pay_money = '0.04';
        }  elseif($pay == 5){   //刷新 推荐信息 和通告信息
            $pay_money = '0.01';
        }

        if(!$from || !$uid || !$pay){
            exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
        }

        $da['from'] = $from;
        $da['account_id'] = $uid;
        $da['order_num'] = $order_num;
        $da['money'] = $pay_money;
        $da['ctime'] = time();
        $da['type'] = $pay;
        M("order")->add($da);


        if($from == 1){
            # 引入微信api
            define('APPID',C("APPID"));
            define('MCHID',C("MCHID"));
            define('KEY',C("KEY"));
            require_once "./api/wxpay/lib/WxPay.Api.php";
            require_once "./api/wxpay/unit/WxPay.JsApiPay.php";
            require_once "./api/wxpay/unit/log.php";
            require_once "./api/wxpay/lib/WxPay.Config.php";
            # 准备参数
            $notify_url = getWebRootUrl().'api/wxpay/xmkp_notify.php';

            if($pay ==1){
                $body = '开通会员一个月';
            }elseif($pay==2){
                $body = '开通会员三个月';
            }elseif($pay==3){
                $body = '开通会员六个月';
            }elseif($pay==4){
                $body = '开通会员十二个月';
            }elseif($pay==5){
                $body = '刷新 通告/推荐 付款';
            }

            try {
                # 统一下单
                $input = new \WxPayUnifiedOrder();
                $input->SetBody($body);
                $input->SetAttach($body);
                $input->SetOut_trade_no($order_num);
                $input->SetTotal_fee((float)$pay_money * 100);
                $input->SetTrade_type("APP");
                $input->SetTime_start(date("YmdHis"));
                $input->SetNotify_url($notify_url);
                $order = \WxPayApi::unifiedOrder($input);

                if($order['return_code'] == 'SUCCESS'){
                    if($order['result_code'] == 'SUCCESS'){
                        $wxvalue = array();
                        $wxvalue['appid'] 		= $order['appid'];
                        $wxvalue['prepayid'] 	= $order['prepay_id'];
//                        $wxvalue['order_num'] 	= $order_num;
                        $wxvalue['partnerid'] 	= $order['mch_id'];
                        $wxvalue['package'] 	= 'Sign=WXPay';
                        $wxvalue['timestamp'] 	= time();
                        $wxvalue['noncestr'] 	= \WxPayApi::getNonceStr();
                        ksort($wxvalue);# 排序

                        $wxstr = $this->ToUrlParams($wxvalue);
                        $string = $wxstr . "&key=".\WxPayConfig::KEY;
                        #签名步骤三：MD5加密
                        $md5string = md5($string);
                        $wxvalue['sign'] = strtoupper($md5string);
                        $wxvalue['code'] = 1;
                        $wxvalue['order_num'] 	= $order_num;
                        $return = $wxvalue;
                    }
                }else{
                    $return['code'] = 0;
                }
                # 返回数据
                exit(json_encode(array('status'=>'200','data'=>$return)));
            } catch (Exception $e) {
                # 提示信息
                exit(json_encode(array('status'=>'201','data'=>"支付失败")));
            }
        }elseif($from == 2){    //支付宝支付
            $notify_url = "http://".$_SERVER['HTTP_HOST'].'/index.php/Api/Zhifu/zfb_notify_url';
            require_once "./api/alipay/AopSdk.php";
            $aop = new \AopClient;                   //实例化
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";   //支付宝网关（固定）
            $aop->appId = "2018011001754247";            //APPID即创建应用后生成
            //下边是私钥
            $aop->rsaPrivateKey = "MIIEpAIBAAKCAQEA1FQSw5ZkclQ3eb75ukcBz2DbtjJFmsV7Nc+D/g/sQ6435jzq8IOPJD09U7f/AJ47K4dK23ZznSoyF8hs2tMeGOF+6uo5qHnBqP/XrVVFtupLLGiTdkFuobvbaqn0dC5KmrymxDax2eNYAwCQ+YJYKOGtaYsWeWa7mbhK+/xqnoj+OCneB6n5pFuWXiWbAEC4YTZv537StC46l/UmslHAD6I7+Ro5FePSI4lx//iRFFZBYAMN3NQOxGcsApJ8Q3R5zw1IfaUEpz2oQuQlbBXSp4HNXjOLgnn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kW/yIvpTKhWnfiPEpRy1i1kKIhs0ECgYBWxzJhIAlbX3ihKmweAqcFGf47NUQIUHBgb8GNs5LSR9cFnNnF0CItj9luExeur0B6qHIBe27/Ku6czqiJSgljcFHlL3ewaT+wVVZ7NWsW9EkmlLqY8LkQjaVQOoj2Z1s7p7ZAvuJsffci72Ap6NcQKU3gzNGBh+amsw6XIjafNw==";
            $aop->format = "json";     //参数返回格式，只支持json
            $aop->charset = "UTF-8";           //请求和签名使用的字符编码格式，支持GBK和UTF-8
            $aop->signType = "RSA2";              //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            //下边是公钥
            $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1FQSw5ZkclQ3eb75ukcBz2DbtjJFmsV7Nc+D/g/sQ6435jzq8IOPJD09U7f/AJ47K4dK23ZznSoyF8hs2tMeGOF+6uo5qHnBqP/XrVVFtupLLGiTdkFuobvbaqn0dC5KmrymxDax2eNYAwCQ+YJYKOGtaYsWeWa7mbhK+/xqnoj+OCneB6n5pFuWXiWbAEC4YTZv537StC46l/UmslHAD6I7+Ro5FePSI4lx//iRFFZBYAMN3NQOxGcsApJ8Q3R5zw1IfaUEpz2oQuQlbBXSp4HNXjOLgnnjcBETH0tkz+3HjLgLHX1925fDTWbAI2RQZBWayUT6oea83m1J8LL73QIDAQAB";
//        $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4yP7iWRavT3f4yLTwn2lRRWmMPE5EiZi6lXSUtM2R0HJGoDbFWQr6fUQ2lIjtwDv6lXo10/Wu1M7MOfwnovSg0JbzjRI706pmcEvfhLftWgyiAWcPu1oL+inAUAzJfeBbPuUNJRdaD7vDz5gMEwlME4g+bgAoGai+Rve9dw1wQzoNCn+S3SFiVZYiDdx4zfCB/hY+GFyXfeXaEqb7uyvM2Oy456y9LIyLIpJHAHOUqh1Xhmq02vm7ZY+Ek5yGK/5cAmOXqI4pjj/+euseGldcWT9EzR5Jqr10v1M6TSYrSCbEw0Qp62F2f4EWwBhLV2OUH+Oa6QkdLxA5LyQpm4pyQIDAQAB";
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            $request = new \AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数

            if($pay ==1){
                $bizcontent = "{\"body\":\"真合拍\","   //商品描述
                    . "\"subject\": \"开通会员一个月\","        // 订单标题
                    . "\"out_trade_no\": \"{$order_num}\","     //   订单编号  随机生成
                    . "\"timeout_express\": \"10m\","              // 多长时间 支付失效
                    . "\"total_amount\": \"{$pay_money}\","        //支付多少钱
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""    //商家和支付宝签约的产品码，为固定值
                    . "}";
            }elseif($pay==2){
                $bizcontent = "{\"body\":\"真合拍\","   //商品描述
                    . "\"subject\": \"开通会员三个月\","        // 订单标题
                    . "\"out_trade_no\": \"{$order_num}\","     //   订单编号  随机生成
                    . "\"timeout_express\": \"10m\","              // 多长时间 支付失效
                    . "\"total_amount\": \"{$pay_money}\","        //支付多少钱
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""    //商家和支付宝签约的产品码，为固定值
                    . "}";
            }elseif($pay==3){
                $bizcontent = "{\"body\":\"真合拍\","   //商品描述
                    . "\"subject\": \"开通会员六个月\","        // 订单标题
                    . "\"out_trade_no\": \"{$order_num}\","     //   订单编号  随机生成
                    . "\"timeout_express\": \"10m\","              // 多长时间 支付失效
                    . "\"total_amount\": \"{$pay_money}\","        //支付多少钱
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""    //商家和支付宝签约的产品码，为固定值
                    . "}";
            }elseif($pay==4){
                $bizcontent = "{\"body\":\"真合拍\","   //商品描述
                    . "\"subject\": \"开通会员十二个月\","        // 订单标题
                    . "\"out_trade_no\": \"{$order_num}\","     //   订单编号  随机生成
                    . "\"timeout_express\": \"10m\","              // 多长时间 支付失效
                    . "\"total_amount\": \"{$pay_money}\","        //支付多少钱
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""    //商家和支付宝签约的产品码，为固定值
                    . "}";
            }elseif($pay==5){
                $bizcontent = "{\"body\":\"真合拍\","   //商品描述
                    . "\"subject\": \"开通会员十二个月\","        // 订单标题
                    . "\"out_trade_no\": \"{$order_num}\","     //   订单编号  随机生成
                    . "\"timeout_express\": \"10m\","              // 多长时间 支付失效
                    . "\"total_amount\": \"{$pay_money}\","        //支付多少钱
                    . "\"product_code\":\"QUICK_MSECURITY_PAY\""    //商家和支付宝签约的产品码，为固定值
                    . "}";
            }




            $request->setNotifyUrl($notify_url);

            $request->setBizContent($bizcontent);
            //这里和普通的接口调用不同，使用的是sdkExecute

            $response = $aop->sdkExecute($request); //发起了预支付订单 还没有支付


            //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
            exit(json_encode(array('status'=>'200','data'=>$response)));
        }
    }


    /**
     * 支付宝充值返回处理页面
     * @access public
     */
    public function zfb_notify_url(){
        file_put_contents('./success6.txt', var_export($_POST['out_trade_no'],TRUE));
        file_put_contents('./success7.txt', var_export($_POST,TRUE));
        file_put_contents('./success8.txt', var_export($_REQUEST,TRUE));

        require_once "./api/alipay/AopSdk.php";
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1FQSw5ZkclQ3eb75ukcBz2DbtjJFmsV7Nc+D/g/sQ6435jzq8IOPJD09U7f/AJ47K4dK23ZznSoyF8hs2tMeGOF+6uo5qHnBqP/XrVVFtupLLGiTdkFuobvbaqn0dC5KmrymxDax2eNYAwCQ+YJYKOGtaYsWeWa7mbhK+/xqnoj+OCneB6n5pFuWXiWbAEC4YTZv537StC46l/UmslHAD6I7+Ro5FePSI4lx//iRFFZBYAMN3NQOxGcsApJ8Q3R5zw1IfaUEpz2oQuQlbBXSp4HNXjOLgnnjcBETH0tkz+3HjLgLHX1925fDTWbAI2RQZBWayUT6oea83m1J8LL73QIDAQAB+D/g/sQ6435jzq8IOPJD09U7f/AJ47K4dK23ZznSoyF8hs2tMeGOF+6uo5qHnBqP/XrVVFtupLLGiTdkFuobvbaqn0dC5KmrymxDax2eNYAwCQ+YJYKOGtaYsWeWa7mbhK+/xqnoj+OCneB6n5pFuWXiWbAEC4YTZv537StC46l/UmslHAD6I7+Ro5FePSI4lx//iRFFZBYAMN3NQOxGcsApJ8Q3R5zw1IfaUEpz2oQuQlbBXSp4HNXjOLgnnjcBETH0tkz+3HjLgLHX1925fDTWbAI2RQZBWayUT6oea83m1J8LL73QIDAQAB";
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");

        if (1) {  //判断成功之后使用getResponse方法判断是否是支付宝发来的异步通知。
            # 商户订单号

            $out_trade_no = $_POST['out_trade_no'];
//            $out_trade_no = 'ZHP151756565717';

            $dingdan = M("order")->where("order_num = '{$out_trade_no}'")->find();
            $use = M("account")->where("id = '{$dingdan['account_id']}'")->find();

            if( $out_trade_no && $_POST['trade_status']=='TRADE_SUCCESS' ){
//            if( $out_trade_no && $trade_status ='TRADE_SUCCESS' ){


                if($dingdan['type'] == 1){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] != 1){
                        $da['etime']=time()+30*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+30*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);
                }elseif($dingdan['type'] == 2){

                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] != 1){
                        $da['etime']=time()+90*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+90*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);
                }elseif($dingdan['type'] == 3){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();

                    if($use['is_member'] != 1){
                        $da['etime']=time()+180*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+180*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);
                }elseif($dingdan['type'] == 4){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] != 1){
                        $da['etime']=time()+365*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+365*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);
                }elseif($dingdan['type'] == 5){

                    $da['is_zhifu'] =  1;
                    $da['is_jia_shaxin'] =  1;    //刷新次数加一
                    $da['zhifu_time'] =  time();
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);

                }
                   $dat['is_zhifu'] = 1;
                   $dat['zhifu_time'] = time();
                   M("order")->where("order_num = '{$out_trade_no}'")->save($dat);

                echo "success";die;        //请不要修改或删除
            } else {
                echo "sign fail";die;
            }
        } else //验证签名失败
        {
            echo "sign fail";die;
        }
    }

    /**
     * 拼接key=>$value
     * @access public
     */
    private function ToUrlParams($wxarr)
    {
        $buff = "";
        foreach ($wxarr as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

    //微信支付回调
    public function wx_zhifu_huidiao(){

        # 引入微信api
        require_once './api/wxpay/lib/WxPay.Api.php';
        require_once './api/wxpay/lib/WxPay.Notify.php';
        require_once './api/wxpay/lib/WxPay.Data.php';
        # 获取数据
        $xml_name = Admin_post('xml_name','');
        $xml_file = 'data/wx_xml/'.$xml_name;

        if( !file_exists($xml_file) ){
            \Log::write($xml_file.'不存在！'.'  '.date('Y-m-d H:i:s'));
        }

        $xml = file_get_contents($xml_file);

        # xml转为数组

        $data = \WxPayResults::Init($xml);

        $rxml_ok = '<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>';
        $rxml_fail = '<xml><return_code>FAIL</return_code><return_msg>FAIL</return_msg></xml> ';

        $input = new \WxPayOrderQuery();

        $input->SetTransaction_id($data['transaction_id']);

        $result = \WxPayApi::orderQuery($input);

        if( $result["return_code"] == "SUCCESS"  && $result["result_code"] == "SUCCESS")
        {
            # 商户订单号
            $out_trade_no = $result['out_trade_no'];#  用户的订单
            if( $out_trade_no ){
                $dingdan = M("order")->where("order_num = '{$out_trade_no}'")->find();
                $use = M("account")->where("id = '{$dingdan['account_id']}'")->find();
                if($dingdan['type'] == 1){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] == 1){
                        $da['etime']=time()+30*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+30*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);

                }elseif($dingdan['type'] == 2){

                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] == 1){
                        $da['etime']=time()+90*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+90*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);
                }elseif($dingdan['type'] == 3){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();

                    if($use['is_member'] == 1){
                        $da['etime']=time()+180*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+180*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);

                }elseif($dingdan['type'] == 4){
                    $da['is_member'] =  1;
                    $da['is_zhifu'] =  1;
                    $da['zhifu_time'] =  time();
                    $da['stime'] =  time();
                    if($use['is_member'] == 1){
                        $da['etime']=time()+365*24*3600;
                    }elseif($use['is_member'] == 1){
                        $da['etime'] = $use['etime']+time()+365*24*3600;
                    }
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);

                }elseif($dingdan['type'] == 5){
                    $da['is_zhifu'] =  1;
                    $da['is_jia_shaxin'] =  1;    //刷新次数加一
                    $da['zhifu_time'] =  time();
                    M("account")->where("id = {$dingdan['account_id']}")->save($da);

                }
                $dat['is_zhifu'] = 1;
                $dat['zhifu_time'] = time();
                M("order")->where("order_num = '{$out_trade_no}'")->save($dat);

                echo $rxml_ok;die;
            } else {
                echo $rxml_fail;die;
            }
        }else{
            $returnxml = '<xml><return_code>FAIL</return_code><return_msg>参数格式校验错误</return_msg></xml> ';
            echo $returnxml;die;
        }
    }


    //确认是否支付成功
    function is_zhifu_success(){
        $order_num = I("order_num");
//        $order_num = "ZHP15167843311";
        if(!$order_num){
            exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
        }
        $data = M("order")->where("order_num = '{$order_num}'")->find();
        $dat = M("account")->where("id = '{$data['account_id']}'")->find();
        $etime =  $dat['etime'];
          if($data['is_zhifu'] == 1 && $etime){

              exit(json_encode(array('status'=>'200','data'=>$etime)));
          }
    }





















}